package com.mune.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mune.gulimall.product.service.CategoryBrandRelationService;
import com.mune.gulimall.product.vo.Catelog2Vo;
import com.sun.corba.se.spi.ior.ObjectKey;
import io.lettuce.core.RedisClient;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mune.common.utils.PageUtils;
import com.mune.common.utils.Query;

import com.mune.gulimall.product.dao.CategoryDao;
import com.mune.gulimall.product.entity.CategoryEntity;
import com.mune.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.lang.model.type.ReferenceType;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
  //可以使用注入,报错不会影响功能
//    @Autowired
//    private CategoryDao categoryDao;
  @Resource
  private RedisTemplate<String, Object> redisTemplate;

  @Autowired
  private CategoryBrandRelationService categoryBrandRelationService;

  @Autowired
  private RedissonClient redisson;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<CategoryEntity> page = this.page(
            new Query<CategoryEntity>().getPage(params),
            new QueryWrapper<CategoryEntity>()
    );

    return new PageUtils(page);
  }

  @Override
  public List<CategoryEntity> listWithTree() {
    // 查出所有分类
    // baseMapper指的就是CategoryDao对象
    List<CategoryEntity> entities = baseMapper.selectList(null);
    // 组装成父子树形结构
    //  找到所有的一级分类
    List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) ->
            categoryEntity.getParentCid() == 0
    ).map((menu) -> {
      menu.setChildren(getChildren(menu, entities));
      return menu;
    }).sorted((menu1, menu2) -> {
      return ( menu1.getSort() == null ? 0 : menu1.getSort() ) - ( menu2.getSort() == null ? 0 : menu2.getSort() );
    }).collect(Collectors.toList());

    return level1Menus;
  }

  @Override
  public void removeMenuByIds(List<Long> asList) {
    //TODO 1、检查当删除的菜单,是否在其他地方被引用
    baseMapper.deleteBatchIds(asList);
  }

  @Override
  public Long[] findCatelogPath(Long catelogId) {
    List<Long> paths = new ArrayList<>();
    findParentPath(catelogId, paths);
    Collections.reverse(paths);
    return paths.toArray(new Long[paths.size()]);
  }

  /**
   * 级联更新所有的关联数据
   *
   * @param category
   */
  @Transactional
  @Override
  public void updateCascade(CategoryEntity category) {
    this.updateById(category);
    categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
  }

  @Override
  public List<CategoryEntity> getLevel1Categorys() {

    List<CategoryEntity> list = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    return list;
  }

  private Map<String, List<Catelog2Vo>> getCatalogJsonDbWithLocalLock() {
    return getDataFromDB();
  }

  private Map<String, List<Catelog2Vo>> getCatalogJsonDbWithRedissonLock() {
    RLock lock = redisson.getLock("catalogJson-lock");
    lock.lock();

    Map<String, List<Catelog2Vo>> dataFromDB;
    try {
      dataFromDB = getDataFromDB();
    } finally {
      lock.unlock();
    }
    return dataFromDB;

  }

  private Map<String, List<Catelog2Vo>> getCatalogJsonDbWithRedisLock() {
    // 占用分布式锁
    String uuid = UUID.randomUUID().toString();
    Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
    if (lock) {
      Map<String, List<Catelog2Vo>> dataFromDB;
      try {
        dataFromDB = getDataFromDB();
      } finally {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
      }
      //String lockValue = (String) redisTemplate.opsForValue().get("lock");
      //if (lockValue.equals(uuid)) {
      //  redisTemplate.delete("lock");
      //}
      return dataFromDB;
    } else {
      try {
        Thread.sleep(200);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return getCatalogJsonDbWithRedisLock();
    }
  }

  private Map<String, List<Catelog2Vo>> getDataFromDB() {
    System.out.println(redisTemplate.getValueSerializer());
    Map<String, List<Catelog2Vo>> catalogJSON = JSON.parseObject((String) redisTemplate.opsForValue().get("catalogJSON"), new TypeReference<Map<String, List<Catelog2Vo>>>() {
    });
    if (catalogJSON != null) {
      return catalogJSON;
    }
    List<CategoryEntity> selectList = baseMapper.selectList(null);

    List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
    Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
      List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
      List<Catelog2Vo> catelog2Vos = null;
      if (categoryEntities != null) {
        catelog2Vos = categoryEntities.stream().map(l2 -> {
          Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
          List<CategoryEntity> category3Entity = getParent_cid(selectList, l2.getCatId());
          if (category3Entity != null) {
            List<Catelog2Vo.Catelog3Vo> collect = category3Entity.stream().map(l3 -> {
              Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
              return catelog3Vo;
            }).collect(Collectors.toList());
            catelog2Vo.setCatalog3List(collect);
          }

          return catelog2Vo;
        }).collect(Collectors.toList());
      }
      return catelog2Vos;
    }));
    return parent_cid;
  }

  @Override
  public Map<String, List<Catelog2Vo>> getCatalogJson() {
    Map<String, List<Catelog2Vo>> catalogJSON = JSON.parseObject((String) redisTemplate.opsForValue().get("catalogJSON"), new TypeReference<Map<String, List<Catelog2Vo>>>() {
    });
    if (catalogJSON == null) {
      catalogJSON = getCatalogJsonDbWithRedissonLock();
      String s = JSON.toJSONString(catalogJSON);
      redisTemplate.opsForValue().set("catalogJSON", s);
    }
    return catalogJSON;
  }

  private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parentCid) {
    return selectList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
  }

  private void findParentPath(Long catelogId, List<Long> paths) {
    paths.add(catelogId);
    CategoryEntity byId = this.getById(catelogId);
    if (byId.getParentCid() != 0) {
      findParentPath(byId.getParentCid(), paths);
    }
  }

  /**
   * 在菜单集合(all)中查找出root的子菜单,
   *
   * @param root 父级菜单
   * @param all  查找的集合
   * @return 子菜单集合
   */
  private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
    List<CategoryEntity> children =
            all.stream().
                    filter(categoryEntity -> {
                      return categoryEntity.getParentCid().equals(root.getCatId());
                    })
                    .map(categoryEntity -> {
                      categoryEntity.setChildren(getChildren(categoryEntity, all));
                      return categoryEntity;
                    })
                    .sorted((menu1, menu2) -> ( menu1.getSort() == null ? 0 : menu1.getSort() ) - ( menu2.getSort() == null ? 0 : menu2.getSort() ))
                    .collect(Collectors.toList());
    return children;
  }

}